package net.pinnoocle.playservice.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.pinnoocle.playcommon.exception.ShopException;
import net.pinnoocle.playcommon.response.ErrorCode;
import net.pinnoocle.playcommon.utils.ConvertUtils;
import net.pinnoocle.playdao.dao.MasterOpenScriptDao;
import net.pinnoocle.playdao.entity.MasterFinance;
import net.pinnoocle.playdao.entity.MasterOpenScript;
import net.pinnoocle.playdao.entity.page.PageModel;
import net.pinnoocle.playdao.entity.page.PageQuery;
import net.pinnoocle.playdao.entity.shopPc.master.CheckOpenScriptPageVo;
import net.pinnoocle.playdao.entity.shopPc.master.OpenScriptDetailVo;
import net.pinnoocle.playdao.entity.shopPc.master.OpenScriptSearchListVo;
import net.pinnoocle.playdao.entity.shopPc.master.UpdateOpenScriptParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 主持人开本(MasterOpenScript)表服务实现类
 *
 * @author ye
 * @since 2021-11-09 11:10:21
 */
@Service("masterOpenScriptService")
@Slf4j
public class MasterOpenScriptServiceImpl extends ServiceImpl<MasterOpenScriptDao, MasterOpenScript> {

    @Autowired
    UserServiceImpl userService;
    @Autowired
    MasterFinanceServiceImpl masterFinanceService;

    /**
     * 开本审核列表
     * @param params
     * @return
     */
    public PageModel<CheckOpenScriptPageVo> openScripts(OpenScriptSearchListVo params){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(params.getPage()));
        pageMap.put("pageSize",String.valueOf(params.getPageSize()));

        if(params.getShopId() == null){
            params.setShopId(userService.getGlobalShopId());
        }
        Page<CheckOpenScriptPageVo> list = this.baseMapper.openScripts(
                new PageQuery<MasterOpenScript>(pageMap).getPage(),params);
        List<CheckOpenScriptPageVo> records = list.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(list, new ArrayList<>());
        }
        return new PageModel<>(list, records);
    }

    /**
     * 开本详情
     * @param openId
     * @return
     */
    public OpenScriptDetailVo scriptDetail(String openId){
        return this.baseMapper.scriptDetail(openId);
    }

    /**
     * 开本编辑
     * @param params
     * @return
     */
    public boolean updateOpenScript(UpdateOpenScriptParams params){
        try {
            MasterOpenScript masterOpenScript = ConvertUtils.sourceToTarget(params, MasterOpenScript.class);
            return this.updateById(masterOpenScript);
        } catch (Exception e) {
            log.info("开本编辑失败："+e.getMessage());
        }
        return true;
    }

    /**
     * 开本审核
     * @param openId
     * @param isCheck
     * @param refuseReason
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean checkOpenScript(String openId,Integer isCheck,String refuseReason){
        int checkResult = isCheck == 1 ? 1 : 2;
        if(checkResult == 2 && StringUtils.isBlank(refuseReason)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"请输入拒绝理由");
        }
        try {
            MasterOpenScript masterOpenScript = this.getById(openId);
            masterOpenScript.setIsCheck(checkResult);
            if(checkResult == 2){
                masterOpenScript.setRefuseReason(refuseReason);
            }
            boolean result = this.updateById(masterOpenScript);
            //通过审核，主持人增加收入
            if(result && isCheck == 1){
                String masterId = masterOpenScript.getMasterId();
                //增加主持人财务明细
                BigDecimal masterBalance = masterFinanceService.getMasterBalance(masterId);
                MasterFinance masterFinance = new MasterFinance();
                masterFinance.setMasterId(masterId);
                masterFinance.setShopId(masterOpenScript.getShopId());
                masterFinance.setIncomeAmount(masterOpenScript.getIncomeAmount());
                masterFinance.setSourceName("剧本收益");
                masterFinance.setBalance(masterBalance.doubleValue());
                masterFinance.setLeftAmount(masterOpenScript.getIncomeAmount());
                masterFinance.setFinanceType(0);//收入
                masterFinance.setCreatedTime(new Date());
                masterFinanceService.save(masterFinance);
                //修改主持人累计金额
                masterFinanceService.updateTotalAmount(masterId,masterOpenScript.getIncomeAmount());
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}